import datetime

from django.shortcuts import render
from rest_framework import serializers
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.headline.serializers.comments import CommentModelSerializer
from apps.headline.serializers.labels import LabelModelSerializer
from apps.headline.serializers.user import UserModelSerializer
from apps.headline.utils.page import PageNumber
from apps.headline.models import Channel, Article, Comment
from apps.headline.serializers import channels
from apps.headline.serializers.articles import ArticlesModelSerializer, ArticlesCreateFindSerializer
# Create your views here.
from rest_framework.generics import ListAPIView, GenericAPIView, CreateAPIView, RetrieveAPIView

from apps.question.models import Label
from apps.users.models import User


class ChannelListAPIView(ListAPIView):
    # 获取频道信息
    queryset = Channel.objects.all()
    serializer_class = channels.ChannelModelSerializer
    pagination_class = PageNumber
    permission_classes = [IsAuthenticated]
    permission_classes = []

    # def get(self, request, *args, **kwargs):
    #     return self.list(request, *args, **kwargs)


class ArticleAPIView(ListAPIView):
    # 查询频道下的文章

    serializer_class = ArticlesModelSerializer
    pagination_class = PageNumber
    permission_classes = []

    def get_queryset(self):
        c_id = self.kwargs.get('id')
        # if c_id == -1:
        c_id = int(c_id)
        if c_id == -1:
            articles = Article.objects.all()
            return articles
        # channel = Channel.objects.get(id=c_id)
        # article = channel.articles.all()
        # channel = Channel.objects.get(id=c_id)
        # articles = channel.articles.all()
        # return articles
        else:
            channel = Channel.objects.get(id=c_id)
            articles = channel.articles.all()
            return articles

    # def get(self, request, id):
    #     instance = self.get_queryset()
    #     serializer = self.get_serializer(instance, many=True)
    #     return Response(serializer.data)
    # get(self ,id)  {"id": 1}
    # def get(self, request, *args, **kwargs):
    #     c_id = self.kwargs.get('id')
    #     if c_id == -1:
    #         self.queryset = Article.objects.all()
    #     channel = Channel.objects.get(id=c_id)
    #     articles = channel.articles.all()
    #     self.queryset = articles
    #
    #     return self.list(request, *args, **kwargs)

    # def get(self, request, id):
    #     channel = Channel.objects.get(id=id)
    #     articles = channel.articles.all()
    #     serializer = self.get_serializer(articles, many=True)
    #     return Response(serializer.data)


class ArticleCreate(APIView):
    # 发布文章
    # permission_classes = [IsAuthenticated]
    permission_classes = []

    def post(self, request):
        data = request.data
        title = data.get('title')
        content = data.get('content')
        image = data.get('image')
        labels = data.get('labels')
        channel_id = data.get('channel')
        user = request.user
        channel = Channel.objects.get(id=channel_id)
        create_time = datetime.datetime.now()
        update_time = create_time
        create_data = {
            'title': title,
            'content': content,
            'image': image,
            'channel': channel,
            'user': user,
            'createtime': create_time,
            'updatetime': update_time,
        }
        article = Article.objects.create(**create_data)
        for i in labels:
            label = Label.objects.get(id=i)
            label.articles.add(article)
            # article.add(label)
            label.save()

        response_data = {
            'articleid': article.id,
            'message': article.content,
            'success': True
        }
        return Response(response_data)


class ArticleDetails(APIView):
    # 文章详情页
    permission_classes = []

    def get(self, request, id):
        article = Article.objects.get(id=id)
        article.thumbup += 1
        article.save()
        labels_list = []
        labels = article.labels.all()
        for obj in labels:
            labels_list.append(obj.id)

        collected_users_list = []
        collect_users = article.collected_users.all()
        for obj in collect_users:
            collected_users_list.append(obj.id)

        user = article.user
        user_serializer = UserModelSerializer(user)
        user_data = user_serializer.data
        comments = article.article_comments.all()
        if len(comments) == 0:
            comments_data = []
        else:
            # 有评论时，查询评论信息
            comments_data = []
            for comment in comments:
                sub_comments = comment.subs.all()
                sub_list = []
                if len(sub_comments) == 0:
                    pass
                else:
                    for sub_comment in sub_comments:
                        sub_comment_serializer = CommentModelSerializer(sub_comment)
                        sub_com_data = sub_comment_serializer.data
                        sub_com_data['subs'] = []
                        sub_list.append(sub_com_data)
                #
                comment_serializer = CommentModelSerializer(comment)
                com_data = comment_serializer.data
                com_data['subs'] = sub_list
                comments_data.append(com_data)
                # comments_data['sub'] = sub_list

        response_data = {
            'id': article.id,
            'user': user_data,
            'comments': comments_data,
            'title': article.title,
            'content': article.content,
            'image': article.image,
            'createtime': article.createtime,
            'updatetime': article.updatetime,
            'visits': article.visits,
            'thumbup': article.thumbup,
            'comment_count': article.comment_count,
            'channel': article.channel.id,
            'labels': labels_list,
            'collected_users': collected_users_list
        }

        return Response(response_data)


class ArticleCollect(APIView):
    # 收藏，取消收藏
    permission_classes = [IsAuthenticated]

    def put(self, request, id):
        user = request.user
        try:
            collecting = user.collected_articles.all()
            for obj in collecting:
                article_id = obj.id
                article = Article.objects.get(id=article_id)
                if article == Article.objects.get(id=id):
                    article.collected_users.remove(user)
                    article.save()
                    return Response({'message': '取消收藏成功', 'success': True})
            else:
                now_article = Article.objects.get(id=id)
                now_article.collected_users.add(user)
                now_article.save()
                response_data = {
                    'message': '收藏成功',
                    'success': True
                }
                return Response(response_data)
        except Exception as e:
            # try:
            #     article = Article.objects.get(id=id)
            # except Exception as e:
            #     return Response({'code': 404})
            # article.collected_users.add(user)
            # article.save()
            # response_data = {
            #     'message': '收藏成功',
            #     'success': True
            # }
            # return Response(response_data)
            return Response({'code': 404})


class PublishComment(APIView):
    # 评论
    permission_classes = []

    def post(self, request, id):
        # 获取评论的用户
        # user = User.objects.get(id=id)
        user = request.user
        article = Article.objects.get(id=id)
        data = request.data
        article_id = data.get('article')
        article_obj = Article.objects.get(id=article_id)
        content = data.get('content')
        parent = data.get('parent')
        response_data = {
            'message': '添加完成',
            'success': True
        }
        if parent is None:
            # 说明评论的是文章
            new_comment = Comment.objects.create(user=user,
                                                 content=content,
                                                 article=article,)
            return Response(response_data)
        comment_obj = Comment.objects.get(id=parent)
        new_comment = Comment.objects.create(user=user,
                                             content=content,
                                             article=article,
                                             parent=comment_obj)
        article.comment_count += 1
        article.save()
        return Response(response_data)
        # article = Article.objects.get(id=id)

# class ArticleCreateAPIView(CreateAPIView):
#     queryset = Article.objects.all()
#     serializer_class = ArticlesCreateModelSerializer
#     # pagination_class = PageNumber
#     permission_classes = []
#     # pass
#     def post(self, request, *args, **kwargs):
#         return self.create(request, *args, **kwargs)


# class ArticleCreateAPIView(CreateAPIView, RetrieveAPIView):
# class ArticleModelViewSet(ModelViewSet):
#     # 发布文章，查询单一文章
#     permission_classes = []
#     serializer_class = ArticlesCreateFindSerializer
#     queryset = Article.objects.all()
#     # lookup_field = 'id'


class LabelListAPIView(ListAPIView):
    permission_classes = []
    serializer_class = LabelModelSerializer
    queryset = Label.objects.all()


# 查询频道列表
channels = ChannelListAPIView.as_view()
# 查询该频道所有的文章
get_articles_by_channel_id = ArticleAPIView.as_view()
# 添加一篇文章
create_article = ArticleCreate.as_view()
# 查询所有标签
list_label = LabelListAPIView.as_view()
# 查询文章详情
article_detail = ArticleDetails.as_view()
# 收藏文章
article_collect = ArticleCollect.as_view()

# 评论文章
publish_comment = PublishComment.as_view()


class ElaticSearchView(APIView):
    def get(self, request):
        text = request.query_params.get('text')
        obj = Article.objects.filter(title__contains=text)
        serializer = ArticlesModelSerializer(instance=obj,many=True)
        re = []
        for i in obj:
            dict = {'id':i.id,
                    'text': '',
                    'title': i.title,
                    'content': i.content,
                    'createtime': i.createtime,}

            re.append(dict)
        data = {"count": len(re),
                "next": '',
                "previous": '',
                "results": re}
        return Response(data)
9
